﻿module Sustainalytics.Portfolio {

    import Common = Sustainalytics.Common;
    import SearchPortfolio = Sustainalytics.Portfolio.PortfolioSearchController;
    import Portfolio = Sustainalytics.Portfolio;
    import LRTM = Sustainalytics.LRTM;

    // Portfolio List controller
    export class PortfolioUploadController {

        public portfolio: PortfolioDto;
        public portfolioFilter: PortfolioFilterDto;
        public isShared: boolean;
        public portfolioSearch: string;
        private accountId: string;
        private userId: string;
        private selectedFile: File;
        private portfolioUpload: PortfolioUploadDto;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private PortfolioService: PortfolioService,
            private PortfolioCompanyService: PortfolioCompanyService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private $modal: Common.IModal,
            private $modalInstance: Common.IModalInstance,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {

            var ctx = this;
            ctx.isShared = false;
            ctx.portfolio = new PortfolioDto();
            ctx.portfolioFilter = new PortfolioFilterDto();
            ctx.portfolioFilter.isMyPortfolio = true;
            ctx.portfolioFilter.isNameEqual = true;

            ctx.portfolioUpload = new PortfolioUploadDto();
            ctx.portfolioSearch = '';

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;
            ctx.portfolioUpload.accountId = ctx.accountId;
            ctx.portfolioUpload.userId = ctx.userId;

            $scope['portfolioAdd'] = ctx;
        }

        public cancel = function (newStatus) {
            var ctx = this;
            ctx.$rootScope['loading'] = false;
            ctx.$modalInstance.close({ newStatus: newStatus });
        };

        public selectPortfolioAdd(item) {
            var ctx = this;
            ctx.portfolio.name = item.name;
            ctx.portfolio.id = item.id;
            ctx.portfolioFilter.namePortfolio = item.name;
        }

        public downloadPortfolioUploadTemplate() {
            var ctx = this;
            var promise = ctx.LongRunningTaskManagerService.runTask('Download securities template ', null, LRTM.LongRunningTaskTypeEnum.PortfolioDownloadTemplate, true, null);
        }

        private showErrorCode(code: number) {
            var ctx = this;
            var msg = ctx.staticObjects.getErrorMesageByStatusCode(code);
            ctx.notificationFactory.error('', msg);
        }

        public onSelectExcel($files): any {
            var ctx = this;
            ctx.selectedFile = null;
            var file = $files[0]; // html assures is just 1
            if (file && (file.type != "application/vnd.ms-excel" && file.type != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                ctx.showErrorCode(5210);
            }
            else if (file) {
                ctx.selectedFile = file;
            }
        }

        public getPortfolioWithTheSameName() {
            var ctx = this;

        }

        public savePortfolioFromUpload() {
            var ctx = this;
            //ctx.$rootScope['loading'] = true;

            var files = $('#portfolioFile').get(0)['files'];
            ctx.portfolioFilter.namePortfolio = ctx.portfolioSearch;
            ctx.portfolioFilter.isNameEqual = true;

            if (files.length > 0 && ctx.portfolioSearch.length > 0) {
                var promiseSearchPortfolio = ctx.PortfolioService.getPortfolios(ctx.portfolioFilter, 0, 1, null, null, ctx.accountId, ctx.userId);

                promiseSearchPortfolio.then(function (portfolio) {
                    var currentPortfolio: PortfolioDto;
                    currentPortfolio = portfolio[0];

                    if (currentPortfolio != null) {
                        //message overwrite
                        var modalInstancePortfolio = ctx.$modal.open({
                            templateUrl: '/Views/Portfolio/portfolioExists_dialog.tpl.html',
                            controller: 'PortfolioCheckController',
                            size: 'lg',
                            backdrop: 'static'
                        });

                        modalInstancePortfolio.result.then((out) => {
                            if (out['portfolioCheck'] == true) {
                                ctx.$rootScope['loading'] = true;
                                ctx.portfolioUpload.portfolioId = currentPortfolio.id;
                                ctx.portfolioUpload.portfolioName = currentPortfolio.name;
                                ctx.portfolioUpload.sharingStatus = ctx.isShared == true ? 2 : 1;

                                var now = new Date();
                                var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
                                ctx.portfolioUpload.insertDate = now_utc;

                                var promise = ctx.LongRunningTaskManagerService.runTaskWithUpload(
                                    'Upload portfolio ', // title
                                    JSON.stringify(ctx.portfolioUpload), // paramJson
                                    Sustainalytics.LRTM.LongRunningTaskTypeEnum.PortfolioUpload, // taskType
                                    files, // files
                                    null, // uploadProgressFunc
                                    true, // isDownload
                                    (id, newStatus, oldStatus, taskInstance) => ctx.statusChangedCallback(id, newStatus, oldStatus, taskInstance) // statusChangedCallback
                                    );
                            }
                            else {
                                var element = document.getElementById("portfolioAddSearchInput");
                                if (element)
                                    element.focus();
                            }
                        });
                    }
                    else {
                        ctx.$rootScope['loading'] = true;
                        ctx.portfolioUpload.portfolioId = null;
                        ctx.portfolioUpload.portfolioName = ctx.portfolioSearch;
                        ctx.portfolioUpload.sharingStatus = ctx.isShared == true ? 2 : 1;

                        var now = new Date();
                        var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
                        ctx.portfolioUpload.insertDate = now_utc;

                        var promise = ctx.LongRunningTaskManagerService.runTaskWithUpload(
                            'Upload task ', // title
                            JSON.stringify(ctx.portfolioUpload), // paramJson
                            Sustainalytics.LRTM.LongRunningTaskTypeEnum.PortfolioUpload, // taskType
                            files, // files
                            null, // uploadProgressFunc
                            true, // isDownload
                            (id, newStatus, oldStatus, taskInstance) => ctx.statusChangedCallback(id, newStatus, oldStatus, taskInstance) // statusChangedCallback
                            );
                    }
                });
            }
            else {
                if (files.length == 0)
                    ctx.showErrorCode(5203);
                if (ctx.portfolioSearch.length == 0)
                    ctx.showErrorCode(5010);
                ctx.$rootScope['loading'] = false;
            }
        }

        public statusChangedCallback(taskInstanceId: string, newStatus: LRTM.LongRunningTaskInstanceStatusEnum, oldStatus: LRTM.LongRunningTaskInstanceStatusEnum, taskInstance: LRTM.LongRunningTaskInstance): void {
            var ctx = this;

            if (newStatus === LRTM.LongRunningTaskInstanceStatusEnum.Failed) {
                var promise = ctx.LongRunningTaskManagerService.getResult(taskInstanceId, false);
                promise.then(function (res) {
                    ctx.$rootScope['loading'] = false;
                    console.log(taskInstance);
                    console.log(taskInstance.status.taskStatus.errors);
                    var serverErrors = taskInstance.status.taskStatus.errors;
                    if (serverErrors && serverErrors.length > 0) {

                        serverErrors.forEach(serverErr => {
                            taskInstance.errors.push(serverErr.arguments[0]);
                        });
                    }
                });
            }

            // display result
            if (newStatus == LRTM.LongRunningTaskInstanceStatusEnum.Finished) {
                var promise = ctx.LongRunningTaskManagerService.getResult(taskInstanceId, false);
                promise.then(function (res) {
                    console.log(taskInstance);
                    if (taskInstance.status.taskStatus.details && taskInstance.status.taskStatus.details.length > 0) {
                        ctx.$rootScope['loading'] = false;
                        ctx.cancel(newStatus);
                        var modalInstanceErrors = ctx.$modal.open(
                            {
                                templateUrl: '/Views/Portfolio/errors_dialog.tpl.html',
                                controller: 'ShowErrorsInModalController',
                                size: 'lg',
                                backdrop: 'static',
                                resolve:
                                {
                                    errors: function () {
                                        return taskInstance.status.taskStatus.details;
                                    }
                                }
                            });
                    }
                });
            }
        }

        public setPrivate = function () {
            var ctx = this;
            ctx.isShared = false;
        }

        public setShared = function () {
            var ctx = this;
            ctx.isShared = true;
        }
    }

    // register controller with News Angular module
    angular.module('Sustainalytics.Portfolio').controller('PortfolioUploadController', function ($rootScope: ng.IScope, $scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, PortfolioService, PortfolioCompanyService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects, $modal: Common.IModal, $modalInstance: Common.IModalInstance, LongRunningTaskManagerService) {
        var ctrl = new Sustainalytics.Portfolio.PortfolioUploadController($rootScope, $scope, $q, $location, PortfolioService, PortfolioCompanyService, notificationFactory, staticObjects, $modal, $modalInstance, LongRunningTaskManagerService);
        return ctrl;
    });
} 
